package com.alibaba.nacos.naming.push.v2.executor;

import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.remote.request.NotifySubscriberRequest;
import com.alibaba.nacos.core.remote.RpcPushService;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.push.v2.PushDataWrapper;
import com.alibaba.nacos.naming.push.v2.task.NamingPushCallback;
import com.alibaba.nacos.naming.utils.ServiceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class PushExecutorRpcImpl
        implements PushExecutor {

    @Autowired
    private RpcPushService rpcPushService;

    @Override
    public void doPush(String clientId,
                       Subscriber subscriber,
                       PushDataWrapper data) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void doPushWithCallback(String clientId,
                                   Subscriber subscriber,
                                   PushDataWrapper data,
                                   NamingPushCallback callback) {
        ServiceInfo serviceInfo = getServiceInfo(data, subscriber);
        callback.setActualServiceInfo(serviceInfo);

        NotifySubscriberRequest notifySubscriberRequest = new NotifySubscriberRequest().setServiceInfo(serviceInfo);
        rpcPushService.pushWithCallback(clientId, notifySubscriberRequest, callback, null);
    }


    private ServiceInfo getServiceInfo(PushDataWrapper data,
                                       Subscriber subscriber) {
        return ServiceUtil.selectInstancesWithHealthyProtection(data.getServiceInfo(), data.getServiceMetadata(), true, true, subscriber);
    }
}
